
import { _decorator, Component, Node, Label, Prefab, instantiate, Vec3 } from 'cc';
import { Game } from "./Game";
const { ccclass, type } = _decorator;

@ccclass('ScorePanel')
export class ScorePanel extends Component {
    /**
     * 奖牌 prefab
     * @private
     */
    @type(Prefab)
    private medalPrefab!: Prefab;
    /**
     * 当前分数对应的奖牌
     * @private
     */
    private currentMedal!: Node;
    /**
     * 当前分数标签
     * @private
     */
    private currentScoreLabel!: Label;
    /**
     * 最高分数标签
     * @private
     */
    private bestScoreLabel!: Label;
    /**
     * 最高分数保存变量
     * @private
     */
    private static bestScore: number = 0;

    /**
     * 加载初始化
     * @private
     */
    private initOnLoad() {
        /**
         * 获取子节点组件
         */
        this.currentScoreLabel = this.node.getChildByName('CurrentScore')!.getComponent(Label)!;
        this.bestScoreLabel = this.node.getChildByName('BestScore')!.getComponent(Label)!;
    }

    /**
     * 组件被激活时
     */
    private onActive(){
        /**
         * 先删除之前的子节点
         */
        this.node.getChildByName('Medal')!.destroyAllChildren();
        /**
         * 获取分数并将其转换为字符串赋值给相应的Label
         */
        this.currentScoreLabel.string = Game.scoreNum.toString();
        if (Game.scoreNum > ScorePanel.bestScore){
            ScorePanel.bestScore= Game.scoreNum;
        }
        this.bestScoreLabel.string = ScorePanel.bestScore.toString();
        /**
         * 根据不同分数显示对应奖牌
         */
        let transformScore: number = Game.scoreNum / 10;
        let medals = instantiate(this.medalPrefab);
        if (transformScore < 1){
            this.currentMedal = medals.getChildByName('Medal_0')!;
        }else if(transformScore < 2){
            this.currentMedal = medals.getChildByName('Medal_1')!;
        }else if(transformScore < 3){
            this.currentMedal = medals.getChildByName('Medal_2')!;
        }else {
            this.currentMedal = medals.getChildByName('Medal_3')!;
        }
        this.node.getChildByName("Medal")!.addChild(this.currentMedal);
    }

    /**
     * 子类实现
     * @protected
     */
    protected onLoad() {
        this.initOnLoad();
    }

    protected update(dt: number) {
        if (this.node.active){
            this.onActive();
        }
    }
}